import { createSelector } from "@ngrx/store";
import { getMapState } from "./map.selector";
import { MapState } from "../reducers";
import { LayersState } from "../reducers/layers.reducer";
import { Layer } from "../../../ngx-ol";
import { LayerTypes } from "../../enums";


export const getLayersState = createSelector(getMapState, (state: MapState) => state.layers);

export const getLayerLoading = createSelector(getLayersState, (state: LayersState) => state.layerLoading);

export const getLayerLoaded = createSelector(getLayersState, (state: LayersState) => state.layerLoaded);

export const getLayerLoadError = createSelector(getLayersState, (state: LayersState) => state.layerLoadError);

export const getLayersEntities = createSelector(getLayersState, (state: LayersState) => state.entities);

export const getAllLayerIds = createSelector(getLayersEntities, entities => Object.keys(entities));

export const getAll = createSelector(
    getLayersEntities,
    entities => Object.keys(entities)
        .map(key => entities[key])
);

export const getAllLayers = createSelector(
    getAll, 
    layers => layers
        .filter(layer => layer.type !== LayerTypes.JSON)
        .sort((before, after) => after.zIndex - before.zIndex)
);

export const getAllDatas = createSelector(
    getAll, 
    layers => layers
        .filter(layer => layer.type === LayerTypes.JSON)
        .sort((before, after) => after.zIndex - before.zIndex)
);

export const getLastRemoveLayer = createSelector(getLayersState, (state: LayersState) => state.lastRemoved);

export const getLayersTotal = createSelector(getAll, layers => layers.length);

export const getLayersSpatialQueryUseable = createSelector(getLayersState, (state: LayersState) => state.spatialQueryUseable);

export const getTables = createSelector(getLayersState, (state: LayersState) => state.tables);

export const getAllLayerTables = createSelector(getLayersEntities, getTables, (entities, tables) => tables.map(key => entities[key]));

export const getLastAddedTable = createSelector(getLayersState, (state: LayersState) => state.lastAddedTable);

export const getLastAddedTableIndex = createSelector(getTables, getLastAddedTable, (tables, lastAddedTable) => tables.indexOf(lastAddedTable));

export const getLastRemovedTable = createSelector(getLayersState, (state: LayersState) => state.lastRemovedTable);

export const getTableState = createSelector(getLayersState, (state: LayersState) => state.tableState);

export const getSelectedFeature = createSelector(getLayersState, (state: LayersState) => state.featureSelected);

export const getDeselectedFeature = createSelector(getLayersState, (state: LayersState) => state.featureDeselected);







